import { ref, toRefs, getCurrentInstance, reactive } from "vue"
import { ElMessage } from "element-plus"
import createDraw from "../../../zondy/lib/draw.js"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
export const useAddNotice = () => {
  const { $http } = getCurrentInstance().appContext.config.globalProperties
  const draw = ref(null)
  const addNoticesource = ref(null)
  const addNoticelayer = ref(null)
  const oneNoticeForm = reactive({
    id: 1,
    tittle: "",
    content: "",
    time: "",
  })
  const noticeForm = reactive({
    tittle: "",
    content: "",
  })
  const addNoticeEle = ref(null)
  addNoticesource.value = new ol.source.Vector({ wrapX: false })
  addNoticelayer.value = new ol.layer.Vector({
    source: addNoticesource.value,
    style: new ol.style.Style({
      //填充色
      fill: new ol.style.Fill({
        color: "rgba(164,205,255, 0.5)",
      }),
      //边线样式
      stroke: new ol.style.Stroke({
        color: "red",
        width: 1,
      }),
    }),
  })
  const reaultList = ref([])
  const noticeList = ref([])
  const bufferFlag = ref(false)
  const viewFlag = ref(false)
  const oneNoticeFlag = ref(false)
  const editNoticeFlag = ref(false)
  const canEdit = ref(true)
  function bufferAnalysis() {
    mapState.value.map.removeLayer(addNoticelayer.value)
    mapState.value.map.addLayer(addNoticelayer.value)
    draw.value = createDraw({ source: addNoticesource.value, type: "LineString" })
    mapState.value.map.addInteraction(draw.value)
    draw.value.on("drawend", endAddNotice, this)
  }
  function endAddNotice(result) {
    var pointObj = new Array()
    for (var i = 0; i < result.feature.getGeometry().getCoordinates().length; i++) {
      var pointGeo = new Zondy.Object.Point2D(result.feature.getGeometry().getCoordinates()[i][0], result.feature.getGeometry().getCoordinates()[i][1])
      pointObj.push(pointGeo)
      var gArc = new Zondy.Object.Arc(pointObj)
      //构成线的折线
      var gAnyLine = new Zondy.Object.AnyLine([gArc])
      //设置线要素的几何信息
      var gline = new Zondy.Object.GLine(gAnyLine)
      //设置要素的几何信息
      var fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] })
      //设置属性结构
      var regAttStr = new Zondy.Object.CAttStruct({
        FldName: ["ID", "道路名称", "车流量", "行政区"],
        FldNumber: 4,
        FldType: ["string", "string", "int", "string"],
      })
      //实例化CAttDataRow类
      var values = [0, 62.566714, 50.803211, 0]
      var valuesRow = new Zondy.Object.CAttDataRow(values, 1)
      //实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
      var featureBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
        ip: "localhost",
        port: 6163,
        //设置要素缓冲分析左半径
        leftRad: 0.0005,
        //设置要素缓冲分析右半径
        rightRad: 0.0005,
      })
      /*设置缓冲分析参数*/
      //设置几何信息
      featureBufBySR.sfGeometryXML = JSON.stringify([fGeom])
      //设置属性结构
      featureBufBySR.attStrctXML = JSON.stringify(regAttStr)
      //设置属性值
      featureBufBySR.attRowsXML = JSON.stringify([valuesRow])
      //设置追踪半径
      featureBufBySR.traceRadius = 0.0001
      //设置缓冲结果的名称以及存放地址
      featureBufBySR.resultName = "gdbp://MapGisLocal/wuhan1/sfcls/buffer" + Date.now()
      //调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析，AnalysisSuccess为回调函数。
      featureBufBySR.execute(bufferAnalysisSuccess, "post", false, "json")
      mapState.value.map.removeInteraction(draw.value)
    }
  }
  let clipName = null
  var clipParam = null
  let resultLayer = ref(null)
  function bufferAnalysisSuccess(result) {
    var clspath = result.results[0].Value
    //实例化ClipByLayer类
    clipName = "gdbp://MapGisLocal/wuhan1/sfcls/clip" + Date.now()
    clipParam = new Zondy.Service.ClipByLayer({
      ip: "localhost",
      port: 6163,
      //源简单要素类的URL
      srcInfo1: "gdbp://MapGisLocal/wuhan1/sfcls/居民区",
      //裁剪框简单要素类的URL
      srcInfo2: clspath,
      //设置结果URL
      desInfo: clipName,
      infoOptType: 0,
    })
    //调用基类的execute方法，执行图层裁剪分析。AnalysisSuccess为结果回调函数
    clipParam.execute(clipSuccess, "post", false, "json")
  }
  function clipSuccess(data) {
    resultLayer.value = new Zondy.Map.GdbpLayer("", [clipName], {
      ip: "localhost",
      port: 6163,
    })
    mapState.value.map.addLayer(resultLayer.value)
    queryByAttribute(clipName, callback)
  }
  function callback(data) {
    if (reaultList.value) {
      reaultList.value = []
    }
    data.SFEleArray.forEach(item => {
      reaultList.value.push({
        name: item.AttValue[4],
        tel: item.AttValue[5],
      })
    })
    bufferFlag.value = true
    mapState.value.map.removeLayer(resultLayer.value)
  }
  function queryByAttribute(gdbName, querySuccess) {
    //初始化查询结构对象，设置查询结构包含几何信息
    var queryStruct = new Zondy.Service.QueryFeatureStruct()
    //是否包含几何图形信息
    queryStruct.IncludeGeometry = true
    //是否包含属性信息
    queryStruct.IncludeAttribute = true
    //是否包含图形显示参数
    queryStruct.IncludeWebGraphic = false
    //实例化查询参数对象
    var queryParam = new Zondy.Service.QueryByLayerParameter(gdbName, {
      resultFormat: "json",
      struct: queryStruct,
    })
    //设置查询分页号
    queryParam.pageIndex = 0
    //设置查询要素数目
    queryParam.recordNumber = 200
    //设置属性条件
    var mapLayer = 0
    queryParam.where = mapLayer
    //queryParam.where = "name='中国'";
    //实例化地图文档查询服务对象
    var queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
      ip: "localhost",
      port: "6163", //访问IGServer的端口号，.net版为6163，Java版为8089
      crossOrigin: "Anonymous",
    })
    //执行查询操作，querySuccess为查询回调函数
    queryService.query(querySuccess)
    mapState.value.map.removeLayer(resultLayer.value)
  }
  async function confirmNotice() {
    var text = ""
    reaultList.value.forEach(item => {
      text += item.name + " "
    })
    text = noticeForm.content + ",受影响的区域有 " + text + "等小区"
    const data = await $http.post("/api/notice", { tittle: noticeForm.tittle, content: text })
    if (data.code == 0) {
      ElMessage({
        message: "发布公告成功",
        type: "success",
        duration: 2000,
      })
      bufferFlag.value = false
      addNoticeEle.value.resetFields()
      addNoticesource.value.clear()
    }
  }
  function cancelNotice() {
    addNoticeEle.value.resetFields()
    bufferFlag.value = false
  }
  async function viewNotice() {
    viewFlag.value = true
    const { result } = await $http.get("/api/notice")
    noticeList.value = result.data
  }
  function viewOneNotice(scope) {
    oneNoticeFlag.value = true
    editNoticeFlag.value = false
    canEdit.value = true
    oneNoticeForm.tittle = scope.row.tittle
    oneNoticeForm.content = scope.row.content
    oneNoticeForm.time = scope.row.time
  }
  function editOneNotice(scope) {
    oneNoticeFlag.value = true
    editNoticeFlag.value = true
    canEdit.value = false
    oneNoticeForm.id = scope.row.id
    oneNoticeForm.tittle = scope.row.tittle
    oneNoticeForm.content = scope.row.content
    oneNoticeForm.time = scope.row.time
  }
  async function confirmEditNotice() {
    const data = await $http.put(`/api/notice/${oneNoticeForm.id}`, {
      tittle: oneNoticeForm.tittle,
      content: oneNoticeForm.content,
    })
    if (data.code == 0) {
      ElMessage({
        message: "修改公告成功",
        type: "success",
        duration: 2000,
      })
    }
    viewNotice()
    oneNoticeFlag.value = false
  }
  async function deleteoneNotice() {
    const data = await $http.delete(`/api/notice/${oneNoticeForm.id}`)
    if (data.code == 0) {
      ElMessage({
        message: "删除公告成功",
        type: "success",
        duration: 2000,
      })
    }
    viewNotice()
    oneNoticeFlag.value = false
  }
  return {
    bufferAnalysis,
    bufferFlag,
    reaultList,
    confirmNotice,
    noticeForm,
    addNoticeEle,
    cancelNotice,
    viewNotice,
    viewFlag,
    noticeList,
    viewOneNotice,
    oneNoticeForm,
    oneNoticeFlag,
    editNoticeFlag,
    editOneNotice,
    canEdit,
    confirmEditNotice,
    deleteoneNotice,
  }
}
